import time

from xjlibrary.MRabbitMQ.useMQ.sendmq import SendMQUse
from xjlibrary.configread import MyConfigParser
from xjlibrary.database_moudel.simple.mysqlclient import MySqlDbConnect, SelctSqlFromDB, ExeSqlToDB
from xjlibrary.myredis.myredisclient import getDataFromRedis
from xjlibrary.our_file_dir.base_dir import BaseDir

curPath = BaseDir.get_file_dir_absolute(__file__)
TopPath = BaseDir.get_upper_dir(curPath, -3)
sPath = BaseDir.get_new_path(TopPath, "download", "chinaeapo", "download", "pages")


# 数据库链接
def MajorDbConnect():
    return MySqlDbConnect(BaseDir.get_upper_dir(curPath, -1), "db.ini")


# 刷新任务池（从数据库获取任务）
def UpdateTaskPool():
    print('UpdateTaskPool ...')
    sql = "SELECT `starttime`,`endtime`,`page` FROM eapopage WHERE stat=0 AND failcount<9 limit 30000;"
    conn = MajorDbConnect()
    rows = SelctSqlFromDB(sql, conn)
    sql = "update eapopage set stat=-1 where stat=0 AND failcount<9 limit 30000;"
    conn = MajorDbConnect()
    ExeSqlToDB(sql, conn)
    return rows

# def SelectProxy():
#     sSql = "SELECT `proxy` FROM `proxy_pool`"
#     # 数据库连接
#     conn = MajorDbConnect()
#     rows = SelctSqlFromDB(sSql, conn)
#     return rows

def readDBProxy():
    return getDataFromRedis(BaseDir.get_upper_dir(curPath, -1), 'db.ini')


class Send(SendMQUse):
    def __init__(self, cofig, queuetest):
        super(Send, self).__init__(cofig, queuetest)

    def UpdateProxyPool(self):
        rows = readDBProxy()
        self.ProxyPool = list(rows)
        print('****** ProxyPool: %d' % len(self.ProxyPool))
        print('current time:' + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))

    def UpdateTaskPool(self):
        """
        重写更新任务
        :return:
        """
        rows = UpdateTaskPool()
        for starttime,endtime,page in rows:
            dic = {
                'starttime': starttime,
                'endtime': endtime,
                'page': page
            }
            self.TaskPool.append(dic)


if __name__ == "__main__":
    config = BaseDir.get_new_path(BaseDir.get_upper_dir(curPath, -1), "db.ini")
    GolobalConfig = MyConfigParser(config).get_configparser().set_keep_keys_case().read_config().conf_to_dict()
    queueCenter2Node = GolobalConfig['get_article']['MQQueueCenter2Node']
    send = Send(config, queueCenter2Node)
    send.UpdateProxyPool()
    send.set_queue_declare(passive=True)
    send.run()
